<template>
  <div v-if="isOpen">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "PageContainer",
  data() {
    return {
      isOpen: false,
      oldHash: null,
    };
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default: false,
    },
    hash: {
      type: String,
      required: false,
      default: "pageContainer",
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.checkOpen();
        // this.$parent.hashIn()
      } else {
        if (document.location.hash === `#${this.hash}`) {
          window.history.back();
        }
        document.body.className = document.body.className.replace(
          " stopScroll",
          ""
        );
        // this.$parent.hashOut()
      }
      this.isOpen = val;
    },
  },
  beforeDestroy() {
    document.body.className = document.body.className.replace(
      " stopScroll",
      ""
    );
  },
  methods: {
    checkOpen() {
      if (this.value) {
        this.isOpen = true;
        document.body.className += " stopScroll";
        this.popstateManage();
      }
    },
    popstateManage() {
      this.oldHash = window.location.hash || undefined;
      window.history.pushState(
        { hash: `#/${this.hash}` },
        `${this.hash}`,
        `#/${this.hash}`
      );

      const callback = (e) => {
        // eslint-disable-next-line no-unused-vars
        const stateHash = e.state && e.state.hash;
        this.$emit("input", false);
        window.removeEventListener("popstate", callback);
      };
      window.addEventListener("popstate", callback);
    },
  },
  created() {
    this.checkOpen();
  },
};
</script>
<style lang="less">
body.stopScroll {
  overflow: hidden;
}
</style>
